<template>
  <div>
    <div class="card" style="margin-bottom: 5px;display: flex;align-items: center">
      <el-input style="width: 260px; margin-right: 5px" placeholder="请输入药品名称查询" v-model="data.name" :prefix-icon="Search" clearable @clear="load"></el-input>
      <el-button type="primary" @click="load">查 询</el-button>
      <el-button @click="reset">重 置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
      <el-button type="danger">批量删除</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-table :data="data.tableData"
                style="width: 100%;display: flex"
                :header-cell-style="{ color: '#333', backgroundColor: '#eaf4ff' }"
                @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="classificationName" label="类别" />
        <el-table-column prop="img" label="图片">
          <template #default="scope">
            <el-image v-if="scope.row.img" :src="data.port+scope.row.img" :preview-src-list="[scope.row.img]" :preview-teleported="true" style="width: 50px;height: 50px;border-radius: 50%;display: block" />
          </template>
        </el-table-column>
        <el-table-column prop="specifications" label="规格" />
        <el-table-column prop="manufacturer" label="厂家" />
        <el-table-column prop="validityPeriod" label="有效期" />
        <el-table-column prop="price" label="价格" />
        <el-table-column prop="number" label="数量" />
        <el-table-column prop="content" label="详情">
          <template v-slot="scope">
            <el-button type="primary" @click="viewContent(scope.row.content)">点击查看</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="primary" icon="Edit" circle @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" icon="Delete" circle></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[5, 10, 20]"
          :total="data.total"
          @current-change="load"
          @size-change="load"
      />
    </div>

    <el-dialog v-model="data.formVisible" title="药品分类信息" width="50%" destroy-on-close>
      <el-form ref="formRef" :model="data.form" :rules="data.rules" label-width="110px" style="padding: 20px 30px 10px 0">
        <el-form-item prop="name" label="名称" >
          <el-input v-model="data.form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="类别" >
          <el-select
              v-model="data.form.classificationId"
              placeholder="请您选择分类"
              size="large"
              style="width: 240px"
          >
            <el-option
                v-for="item in data.classificationData"
                :key="item.id"
                :label="item.title"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="img" label="图片" >
          <el-upload
              action="http://localhost:8888/files/upload"
              :headers="{ token: data.user.token }"
              :on-success="handleFileSuccess"
              list-type="picture"
              :limit="1"
              :on-exceed="handleExceed"
          >
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="specifications" label="规格" >
          <el-input v-model="data.form.specifications" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="manufacturer" label="厂家" >
          <el-input v-model="data.form.manufacturer" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="validityPeriod" label="有效期" >
          <el-input v-model="data.form.validityPeriod" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="price" label="价格" >
          <el-input v-model="data.form.price" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="number" label="数量" >
          <el-input v-model="data.form.number" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="content" label="攻略详情">
          <div style="border: 1px solid #ccc; width: 100%">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="data.form.content"
                :mode="mode"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      <!--            TODO-->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="data.viewVisible" title="攻略信息" width="40%" destroy-on-close>
      <div v-html="data.content" style="padding: 0 20px"></div>
    </el-dialog>

  </div>
</template>

<script setup>
import { reactive, ref, onBeforeUnmount, shallowRef, onMounted } from "vue";
import {Search} from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const data = reactive({
  port: 'http://localhost:8888',
  user: JSON.parse(localStorage.getItem("code_user") || '{}'),
  username:null,
  name:null,
  pageNum: 1,
  pageSize: 5,
  total: 0,
  tableData: [],
  formVisible:false,
  form:{},
  rules: {
    name: [
      { required: true, message: '请输入药品名称', trigger: 'blur' }
    ],
    classification: [
      { required: true, message: '请输入药品类别', trigger: 'blur' }
    ],
    specifications: [
        { required: true, message: '请输入药品规格', trigger: 'blur' }
    ],
    manufacturer: [
        { required: true, message: '请输入药品厂家', trigger: 'blur' }
    ],
    validityPeriod: [
        { required: true, message: '请输入药品有效期', trigger: 'blur' }
    ],
    number: [
        { required: true, message: '请输入药品数量', trigger: 'blur' }
    ],
    price: [
        { required: true, message: '请输入药品价格', trigger: 'blur' }
    ]
  },
  rows:[],
  ids:[],
  classificationData:[],
  content: '',
  viewVisible: false,
})

const formRef = ref()

/* wangEditor5 初始化开始 */
const editorRef = shallowRef()  // 编辑器实例，必须用 shallowRef
const mode = 'default'
const editorConfig = {MENU_CONF: {}}
// 图片上传配置
editorConfig.MENU_CONF['uploadImage'] = {
  headers: {
    token: data.user.token,
  },
  server: 'http://localhost:9999/files/wang/upload',  // 服务端图片上传接口
  fieldName: 'file'  // 服务端图片上传接口参数
}
// 组件销毁时，也及时销毁编辑器，否则可能会造成内存泄漏
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
// 记录 editor 实例，重要！
const handleCreated = (editor) => {
  editorRef.value = editor
}
/* wangEditor5 初始化结束 */

const load = () =>{
  request.get('/drug/drugClassification/selectDrugDetailsPage',{
    params:{
      pageNum:data.pageNum,
      pageSize:data.pageSize,
      name:data.name
    }
  }).then(res => {
    if (res.code === '200'){
      data.tableData = res.data.list
      data.total = res.data.total
    }else {
      ElMessage.error(res.msg)
    }
  })
}
load()

const reset = () =>{
  data.username = null
  data.name = null
  load()
}

const handleAdd = () => {
  data.formVisible = true
  data.form = {}
}

const handleSubmit = () => {
  formRef.value.validate(valid => {
    if (valid){ //验证通过的情况下
      request.post('/drug/drugClassification/addDrugDetails',data.form).then(res => {
        if (res.code === '200') {
          data.formVisible = false
          ElMessage.success("新增数据成功")
          //刷新表单
          load()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

const handleEdit = (row) => {
  // data.form = row // 浅拷贝
  // console.log(row)
  data.form = JSON.parse(JSON.stringify(row)) // 深拷贝
  data.formVisible = true
}

const update = () => {
  request.put('/drug/drugDetails/updateDrugDetails', data.form).then(res => {
    if (res.code === '200') {
      data.formVisible = false
      ElMessage.success("修改数据成功")
      //刷新表单
      load()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

//兼容新增和修改
const save = () => {
  if (data.form.id) {
    update()
  } else {
    handleSubmit()
  }
}

const handleDelete = (id) => {
  ElMessageBox.confirm(
      '删除后无法恢复，您确定删除吗',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
    request.delete('/drug/drugClassification/deleteDrugClassification/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success("删除成功")
        //刷新表单
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
    ElMessage.info('已取消删除')
  })
}

// rows就是实际选择的数组
const handleSelectionChange = (rows) => {
  // console.log(rows)
  data.rows = rows
  // console.log({data:data.rows})
  data.ids = data.rows.map(item => item.id) //map可以把对象数组转换为一个纯数字数组
}

const deleteBatch = () => {
  if (data.rows.length === 0) {
    ElMessage.warning("请选择要删除的数据")
    return
  }
  ElMessageBox.confirm(
      '删除后无法恢复，您确定删除吗',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
    request.delete('/drug/drugClassification/deleteBatchDrugClassification', {data: data.rows}).then(res => {
      if (res.code === '200') {
        ElMessage.success("删除成功")
        //刷新表单
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
    ElMessage.info('已取消删除')
  })
}

const handleFileSuccess = (res) => {
  if (res.code === '200') {
    data.form.img = res.data
    ElMessage.success("上传成功")
  } else {
    ElMessage.error(res.msg)
  }
}
//TODO
const handleExceed = (files, fileList) => {
  ElMessage.warning("只能上传一张头像");
};

const loadCategory = () => {
  request.get('/drug/drugDetails/selectDrugClassificationAll').then(res => {
    if (res.code === '200') {
      // console.log(res.data)
      data.classificationData = res.data.filter(item => item.name).map(item => ({
        id: item.id,
        title: item.name || '未知分类'  // 如果 name 不存在，给一个默认值
      }));
    } else {
      ElMessage.error(res.msg)
    }
  })
}

loadCategory()

const viewContent = (content) => {
  data.viewVisible = true
  data.content = content
}

</script>

